<route lang="json5">
{
  style: {
    navigationBarTitleText: '我们'
  }
}
</route>

<script lang="ts" setup>
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import { ref, computed, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useSupabaseCoupleStore } from '@/store/supabaseCouple'

import 'dayjs/locale/zh-cn'

defineOptions({
  name: 'CoupleProfile',
})
dayjs.extend(relativeTime)
dayjs.locale('zh-cn')

const coupleStore = useSupabaseCoupleStore()
const localCoverImage = ref('')
const currentRole = ref<'user1' | 'user2' | ''>('')
const currentRoleName = computed(() => {
  if (currentRole.value === 'user1')
    return coupleStore.profile?.user1.name || 'user1'
  if (currentRole.value === 'user2')
    return coupleStore.profile?.user2.name || 'user2'
  return '未设置'
})

// 计算恋爱天数
const loveDays = computed(() => {
  if (!coupleStore.profile?.relationshipStart)
    return 0
  return dayjs().diff(dayjs(coupleStore.profile.relationshipStart), 'day')
})

// 计算下个纪念日
const nextAnniversary = computed(() => {
  if (!coupleStore.profile?.relationshipStart)
    return null
  const start = dayjs(coupleStore.profile.relationshipStart)
  const thisYear = dayjs().year()
  let nextDate = start.year(thisYear)

  if (nextDate.isBefore(dayjs())) {
    nextDate = nextDate.year(thisYear + 1)
  }

  return {
    date: nextDate.format('YYYY-MM-DD'),
    daysLeft: nextDate.diff(dayjs(), 'day'),
  }
})

// 获取最近的照片作为共同回忆
const recentPhotos = computed(() => {
  const allPhotos: any[] = []

  // 从所有相册中收集照片
  coupleStore.albums.forEach((album) => {
    album.photos.forEach((photo) => {
      allPhotos.push({
        url: photo.url,
        date: photo.uploadedAt,
        albumName: album.title,
      })
    })
  })

  // 按日期排序，取最新的6张
  return allPhotos
    .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
    .slice(0, 6)
})

// 总照片数
const totalPhotos = computed(() => {
  return coupleStore.albums.reduce((total, album) => total + album.photos.length, 0)
})

// 跳转到编辑页面
function goToEdit() {
  uni.navigateTo({
    url: '/pages/profile/edit',
  })
}

// 跳转到设置页面
function goToSettings() {
  uni.navigateTo({
    url: '/pages/settings/index',
  })
}

// 跳转到纪念日页面
function goToAnniversary() {
  uni.navigateTo({
    url: '/pages/anniversary/index',
  })
}

// 跳转到倒计时页面
function goToCountdown() {
  uni.navigateTo({
    url: '/pages/countdown/index',
  })
}

// 跳转到愿望清单
function goToWishlist() {
  uni.navigateTo({
    url: '/pages/wishlist/index',
  })
}

// 跳转到约会记录
function goToDateRecords() {
  uni.navigateTo({
    url: '/pages/date-records/index',
  })
}

// 跳转到礼物记录
function goToGifts() {
  uni.navigateTo({
    url: '/pages/gifts/index',
  })
}

// 跳转到身份设置
function goToWhoAmI() {
  uni.navigateTo({
    url: '/pages/whoami/index',
  })
}

// 跳转到相册
function goToAlbum() {
  uni.switchTab({
    url: '/pages/album/index',
  })
}

// 预览照片
function previewPhoto(photo: any) {
  uni.previewImage({
    urls: [photo.url],
    current: photo.url,
  })
}

// 格式化日期
function formatDate(date: string) {
  return dayjs(date).format('MM-DD')
}

onMounted(() => {
  if (!coupleStore.profile) {
    coupleStore.initProfile()
  }
})

onShow(() => {
  // 每次页面显示时，都从本地存储加载封面图片
  localCoverImage.value = uni.getStorageSync('cover_image_local') || ''
  // 身份检查与显示
  const role = uni.getStorageSync('whoAmI') as 'user1' | 'user2' | ''
  const userId = uni.getStorageSync('whoAmI_userId') as string
  currentRole.value = role || ''
  if (!role || !userId) {
    // 未设置身份，默认弹出选择
    setTimeout(() => uni.navigateTo({ url: '/pages/whoami/index' }), 0)
  }
})
</script>

<template>
  <view class="profile-container">
    <!-- 封面区域 -->
    <view class="cover-section">
      <!-- 背景图 -->
      <image
        :src="localCoverImage || coupleStore.profile?.coverImage || '/static/images/default_cover.jpg'"
        class="cover-image"
        mode="aspectFill"
      />
      <!-- 遮罩层 -->
      <view class="cover-overlay" />

      <!-- 头像 -->
      <view class="avatars-container">
        <image :src="coupleStore.profile?.user1.avatar || '/static/images/he.png'" class="avatar he-avatar" mode="aspectFill" />
        <image :src="coupleStore.profile?.user2.avatar || '/static/images/she.png'" class="avatar she-avatar" mode="aspectFill" />
      </view>

      <!-- 文字信息 -->
      <view class="couple-info-container">
        <view class="names">
          {{ coupleStore.profile?.user1.name || '他' }} & {{ coupleStore.profile?.user2.name || '她' }}
        </view>
        <view class="love-days">
          相恋第 {{ loveDays }} 天
        </view>
        <view class="role-pill" @click="goToWhoAmI">
          我的身份：{{ currentRoleName }}
        </view>
      </view>

      <!-- 编辑按钮 -->
      <view class="edit-btn" @click="goToEdit">
        <wd-icon name="edit" size="20px" color="#fff" />
      </view>
    </view>

    <!-- 统计卡片 -->
    <view class="stats-section">
      <view class="stat-card" @click="goToCountdown">
        <view class="stat-number">
          {{ loveDays }}
        </view>
        <view class="stat-label">
          相恋天数
        </view>
      </view>
      <view class="stat-card" @click="goToAnniversary">
        <view class="stat-number">
          {{ nextAnniversary?.daysLeft || 0 }}
        </view>
        <view class="stat-label">
          距离纪念日
        </view>
      </view>
      <view class="stat-card">
        <view class="stat-number">
          {{ totalPhotos }}
        </view>
        <view class="stat-label">
          共同回忆
        </view>
      </view>
    </view>

    <!-- 共同回忆 -->
    <view class="memories-section">
      <view class="section-title">
        <text>💕 共同回忆</text>
        <view class="more-btn" @click="goToAlbum">
          查看更多
        </view>
      </view>
      <view class="memories-grid">
        <view
          v-for="(photo, index) in recentPhotos"
          :key="index"
          class="memory-item"
          @click="previewPhoto(photo)"
        >
          <image :src="photo.url" class="memory-image" mode="aspectFill" />
          <view class="memory-overlay">
            <text class="memory-date">{{ formatDate(photo.date) }}</text>
          </view>
        </view>
        <view v-if="recentPhotos.length === 0" class="empty-memories">
          <text class="empty-text">还没有共同回忆</text>
          <text class="empty-tip">快去相册添加美好瞬间吧~</text>
        </view>
      </view>
    </view>

    <!-- 功能菜单 -->
    <view class="menu-section">
      <wd-cell-group>
        <wd-cell
          title="🎀 纪念日管理"
          is-link
          @click="goToAnniversary"
        />
        <wd-cell
          title="⏰ 甜蜜倒计时"
          is-link
          @click="goToCountdown"
        />
        <wd-cell
          title="⭐ 愿望清单"
          is-link
          @click="goToWishlist"
        />
        <wd-cell
          title="💕 约会记录"

          is-link
          @click="goToDateRecords"
        />
        <wd-cell
          title="🎁 礼物记录"

          is-link
          @click="goToGifts"
        />
        <wd-cell
          title="👤 我的身份设置"
          value="发布动态用的身份"
          is-link
          @click="goToWhoAmI"
        />
      </wd-cell-group>
    </view>

    <!-- 恋爱故事 -->
    <view v-if="coupleStore.profile?.story" class="story-section">
      <view class="section-title">
        我们的故事
      </view>
      <view class="story-content">
        {{ coupleStore.profile.story }}
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.profile-container {
  min-height: 100vh;
  background-color: #fff0f5;
  background-image:
    radial-gradient(circle at 25% 25%, rgba(255, 228, 225, 0.4) 2px, transparent 0),
    radial-gradient(circle at 75% 75%, rgba(255, 228, 225, 0.4) 2px, transparent 0);
  background-size: 20px 20px;
}

.cover-section {
  position: relative;
  height: 280px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(255, 135, 171, 0.2);

  .cover-image {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 1;
  }

  .cover-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(to bottom, rgba(0, 0, 0, 0.05), rgba(0, 0, 0, 0.4));
    z-index: 2;
  }

  .avatars-container {
    position: relative;
    z-index: 3;
    display: flex;
    align-items: center;
    margin-bottom: 12px;

    .avatar {
      width: 72px;
      height: 72px;
      border-radius: 50%;
      border: 3px solid #ffc2d1;
      box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15);

      &.he-avatar {
        animation: float-left 4s ease-in-out infinite;
      }

      &.she-avatar {
        animation: float-right 4s ease-in-out infinite 1.5s;
      }
    }
  }

  .couple-info-container {
    position: relative;
    z-index: 3;
    color: white;
    text-align: center;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.6);

    .names {
      font-size: 20px;
      font-weight: bold;
      margin-bottom: 6px;
    }

    .love-days {
      font-size: 14px;
      opacity: 0.95;
    }

    .role-pill {
      margin-top: 10px;
      display: inline-block;
      padding: 5px 12px;
      border-radius: 999px;
      background: rgba(255, 255, 255, 0.2);
      backdrop-filter: blur(5px);
      color: #fff;
      font-size: 12px;
      border: 1px solid rgba(255, 255, 255, 0.3);
    }
  }

  .edit-btn {
    position: absolute;
    top: 16px;
    right: 16px;
    z-index: 4;
    width: 36px;
    height: 36px;
    background: rgba(0, 0, 0, 0.25);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    backdrop-filter: blur(5px);
  }
}

.card-base {
  background: #ffffff;
  border-radius: 24px;
  padding: 20px;
  margin: 16px;
  box-shadow:
    0 4px 16px rgba(255, 105, 180, 0.1),
    0 10px 30px rgba(255, 105, 180, 0.15);
  border: 1px solid white;
}

.stats-section {
  display: flex;
  gap: 12px;
  padding: 0 16px;
  margin-top: -30px; // 让卡片向上移动，部分覆盖封面
  position: relative;
  z-index: 10;

  .stat-card {
    flex: 1;
    background: #ffffff;
    border-radius: 18px;
    padding: 16px;
    text-align: center;
    box-shadow: 0 6px 18px rgba(255, 135, 171, 0.12);
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-4px);
      box-shadow: 0 8px 24px rgba(255, 135, 171, 0.18);
    }

    .stat-number {
      font-size: 22px;
      font-weight: bold;
      color: #ff69b4;
      margin-bottom: 4px;
    }

    .stat-label {
      font-size: 12px;
      color: #999;
    }
  }
}

.memories-section {
  @extend .card-base;

  .section-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 18px;
    font-weight: bold;
    color: #444;
    margin-bottom: 16px;

    .more-btn {
      font-size: 13px;
      color: #ff69b4;
      padding: 6px 12px;
      border-radius: 16px;
      background: #fff0f5;
      border: 1px solid #ffdde5;
    }
  }

  .memories-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 10px;

    .memory-item {
      position: relative;
      aspect-ratio: 1;
      border-radius: 16px;
      overflow: hidden;
      transition: transform 0.3s ease;

      &:hover {
        transform: scale(1.05);
      }

      .memory-image {
        width: 100%;
        height: 100%;
      }

      .memory-overlay {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
        padding: 10px 8px 6px;

        .memory-date {
          color: white;
          font-size: 11px;
        }
      }
    }

    .empty-memories {
      grid-column: 1 / -1;
      text-align: center;
      padding: 40px 20px;
      color: #aaa;

      .empty-text {
        display: block;
        font-size: 14px;
        margin-bottom: 8px;
      }

      .empty-tip {
        display: block;
        font-size: 12px;
        color: #ff69b4;
      }
    }
  }
}

.menu-section {
  margin: 0 16px;
  border-radius: 24px;
  overflow: hidden;
  box-shadow:
    0 4px 16px rgba(255, 105, 180, 0.1),
    0 10px 30px rgba(255, 105, 180, 0.15);
}

.story-section {
  @extend .card-base;

  .section-title {
    font-size: 18px;
    font-weight: bold;
    color: #444;
    margin-bottom: 12px;
  }

  .story-content {
    font-size: 14px;
    line-height: 1.7;
    color: #666;
  }
}

/* 动画效果 */
@keyframes float-left {
  0%,
  100% {
    transform: translateY(0) rotate(-4deg);
  }
  50% {
    transform: translateY(-8px) rotate(4deg);
  }
}

@keyframes float-right {
  0%,
  100% {
    transform: translateY(0) rotate(4deg);
  }
  50% {
    transform: translateY(-8px) rotate(-4deg);
  }
}

@keyframes glow-text {
  from {
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  }
  to {
    text-shadow:
      0 2px 4px rgba(0, 0, 0, 0.3),
      0 0 15px rgba(255, 255, 255, 0.4);
  }
}
</style>
